﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.ModelBinding;
using Cofe.Core;
using Cofe.Core.Implements;
using Cofe.Web.Interfaces;
using Cofe.Web.Utils;

namespace Cofe.Web.Implements
{
    [Export(typeof(ICofeService))]
    [ServicePriority(ServicePriorityAttribute.DefaultPriority_COFEWS)]
    public class EntryRequestFormatter : IHttpRequestMessageFormatter
    {
        public bool CanCreateRequestObject(HttpRequestMessage request, Type outputType, ParameterDic parameters)
        {
            if (!(MediaFormatterUtils.CanFormatAsJObject(request.Content)))
                return false;

            return outputType.Equals(typeof(CofeSystemInfo)) ||
                outputType.Equals(typeof(IEnumerable<CofeSystemInfo>)) ||
                outputType.Equals(typeof(WebEntryList));
        }

        public object CreateRequestObject(HttpRequestMessage request, Type outputType, ParameterDic parameters)
        {
            var data = MediaFormatterUtils.FormatAsJObjectAsync(request.Content).Result;            
            IEntrySerializerHelper[] helpers =
                parameters.EntrySerializerHelpers != null ? parameters.EntrySerializerHelpers :
                 new IEntrySerializerHelper[] {
                    EntrySerializerHelpers.FindUsingId,
                    EntrySerializerHelpers.FindUsingParseName,
                    EntrySerializerHelpers.UpdateToCache
                  };
        
            if (outputType.Equals(typeof(CofeSystemInfo)))
                return CofeServices.EntrySerializer.ReadEntry(data, helpers);
            
            var el = CofeServices.EntrySerializer.ReadEntryList(data, helpers);
            if (outputType.Equals(typeof(WebEntryList)))
                return el;

            if (outputType.Equals(typeof(IEnumerable<CofeSystemInfo>)))
                return el.Entries;

            throw new NotSupportedException();
        }

        #region Data

        #endregion

        #region Public Properties
        
        #endregion
    }
}
